package com.bmth.alise.client.utils;

import java.net.InetAddress;

import org.elasticsearch.action.index.IndexRequestBuilder;
import org.elasticsearch.client.Client;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.transport.InetSocketTransportAddress;

import com.bmth.alise.client.config.Configuration;

public class ElasticsearchTemplate {
	private static Client client;
	private static IndexRequestBuilder prepareIndex;

	public static void init() {
		try {
			String clusterName = Configuration.getProperty("ClusterName");
			String host = Configuration.getProperty("ElasticHost");
			int port = Integer.parseInt(Configuration.getProperty("ElasticPort"));
			String index = Configuration.getProperty("ESIndex");
			String type = Configuration.getProperty("ESType");

			Settings settings = Settings.settingsBuilder().put("cluster.name", clusterName)
					.put("client.transport.sniff", true).build();

			client = TransportClient.builder().settings(settings).build()
					.addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName(host), port));
			prepareIndex = client.prepareIndex(index, type);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public static void addDoc(String id, String doc) {
		if (prepareIndex == null) {
			init();
		}
		prepareIndex.setSource(doc).setId(id).get();
	}
}
